package com.huixuebao.api.controller.pay;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huixuebao.api.entity.CourseEntity;
import com.huixuebao.api.mapper.CourseMapper;
import com.huixuebao.api.service.rpc.WxPayService;
import com.huixuebao.api.util.pay.PayUtil;
import com.huixuebao.common.bean.ApiResult;
import com.huixuebao.payinterface.dto.PayDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;


/**
 * 微信支付操作接口
 *
 * @version 1.0
 * @date 2020-12-01 20:44
 */
@Slf4j
@RestController()
@RequestMapping("/wxPay")
public class WxPayController {

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    WxPayService wxPayService;

    /**
     * 向前端获取code
     * @param code
     * @return
     */
    @GetMapping("/getUserCode")
    public ApiResult getUserCode(@RequestParam String code) {
        return wxPayService.getUserCode(code);
    }
    /**
     * 生成订单向微信支付发起支付
     * @param payDTO
     * @return
     */
    @PostMapping("/createOrder")
    public ApiResult createOrder(@RequestBody  PayDTO payDTO) {
        CourseEntity entity = courseMapper.selectOne(new LambdaQueryWrapper<CourseEntity>()
                .eq(CourseEntity::getCourseNo, payDTO.getCourseId()));
        boolean result = PayUtil.validatePayAmount(entity.getCoursePrice(), entity.getSettlePrice(), new BigDecimal(payDTO.getPrice()));
        log.info("##########前端传回的价格{}:" + payDTO.getPrice());
        log.info("##########后端的计算值{}:" + result);
        if (result) {
            return wxPayService.createOrder(payDTO);
        } else {
            ApiResult apiResult = new ApiResult();
            apiResult.setSuccess(false);
            log.error("当前支付金额不等于实际支付金额,请从新计算！");
            apiResult.setMessage("当前支付金额不等于实际支付金额");
            return apiResult;
        }
    }
    /**
     * 微信回调接口
     * @param xmlDate
     * @return
     */
    @RequestMapping("/notify")
    public String notify(@RequestBody String xmlDate) {
        return wxPayService.notify(xmlDate);
    }
    /**
     * 如果理赔订单大于课程价格客户支付为0元，后弹更新订单状态即可
     * @param payDTO
     * @return
     */
    @PostMapping("/updateOrder")
    public ApiResult updateOrder(@RequestBody PayDTO payDTO){return wxPayService.updateOrder(payDTO);}

    /**
     * 根据保单号查询支付订单详情
     * @param policyId
     * @return
     */
    @GetMapping("/getSettleDetails")
    public ApiResult getSettleDetails(@RequestParam String policyId){
        return wxPayService.settleDetails(policyId);
    }
}